package com.aabte.cases;

import com.aabte.config.TestConfig;
import com.aabte.model.AddUserCase;
import com.aabte.model.User;
import com.aabte.utils.DatabaseUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.IOException;

public class AddUserTest {

    @Test(dependsOnGroups = "loginTrue",
            description = "添加用户接口测试")
    public void addUser() throws IOException, InterruptedException {
        SqlSession session = DatabaseUtil.getSqlSession();
        AddUserCase addUserCase = session.selectOne("addUserCase", 1);
        System.out.println(addUserCase);
        System.out.println(TestConfig.addUserUrl);

        // 先删除
        session.delete("beforeAddUser", addUserCase.getUsername());
        session.commit(true);
        Thread.sleep(3000);

        // 发请求，获取结果
        String result = gerResult(addUserCase);

        // 验证返回结果
        User user = session.selectOne("addUser", addUserCase);
        System.out.println(user);
        Assert.assertEquals(addUserCase.getExpected(), result);

    }

    private String gerResult(AddUserCase addUserCase) throws IOException {
        HttpPost post = new HttpPost(TestConfig.addUserUrl);

        // 准备参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", addUserCase.getUsername());
        jsonObject.put("password", addUserCase.getPassword());
        jsonObject.put("sex", addUserCase.getSex());
        jsonObject.put("age", addUserCase.getAge());
        jsonObject.put("permission", addUserCase.getPermission());
        jsonObject.put("isDelete", addUserCase.getIsDelete());

        StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
        post.setEntity(entity);

        // 添加头信息
        post.addHeader("content-type", "application/json");

        // 新API无需设置Cookies
        // TestConfig.defaultHttpClient.setCookieStore(TestConfig.cookieStore);
        String result;
        HttpResponse response = TestConfig.httpClient.execute(post);
        result = EntityUtils.toString(response.getEntity());

        return result;
    }

}
